package com.heima.wemedia.delay;

import com.heima.common.delayTask.RedisDelayQueueHandler;
import com.heima.common.delayTask.RedisDelayedQueueUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.TimerTask;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

@Slf4j
@Component
public class RedisDelayedQueueInit implements ApplicationContextAware{

    private ApplicationContext context;
    @Autowired
    private RedisDelayedQueueUtil redisDelayedQueueUtil;



    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.context = applicationContext;
    }

    @PostConstruct
    public void run() throws Exception {
        ScheduledExecutorService executorService = Executors.newScheduledThreadPool(3);
        executorService.scheduleAtFixedRate(new TimerTask() {
            @Override
            public void run() {
                try {
                    Object queue = redisDelayedQueueUtil.getDelayQueue("wm.news.pub");
                    RedisDelayQueueHandler handler = (RedisDelayQueueHandler)context.getBean("publicNewsDelayHandler");
                    handler.execute(queue);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        },0,1, TimeUnit.SECONDS);
        log.info("延迟队列监听成功！！");
        
//        初始化完成后，向队列添加一个无用的元素
        redisDelayedQueueUtil.addQueue(0,1, TimeUnit.SECONDS,"wm.news.pub");
    }
}